package com.cskaoyan.wordmemorize.common.upload;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.cskaoyan.wordmemorize.service.FileUploadService;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Slf4j
@Service
@ConditionalOnBean(AliOssProperties.class)
public class AliOssStorageServiceImpl implements FileUploadService {
    @Resource
    private AliOssProperties aliOssProperties;


    /**
     * 文件上传
     */
    @Override
    public String upload(MultipartFile file) throws IOException {
        // 构造桶中的对象名称
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = UUID.randomUUID() + extension;

        // todo 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(
                aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret());

        try {
            // todo 向桶中放入指定名称的对象
            ossClient.putObject(aliOssProperties.getBucketName(), objectName, file.getInputStream());

            // todo 文件访问路径规则 https://BucketName.Endpoint/ObjectName
            StringBuilder stringBuilder = new StringBuilder("https://");
            stringBuilder.append(aliOssProperties.getBucketName())
                    .append(".")
                    .append(aliOssProperties.getEndpoint())
                    .append("/")
                    .append(objectName);

            // todo 返回访问文件的url
            return stringBuilder.toString();
        } catch (OSSException oe) {
            log.error("阿里OSS异常，Error Message:{}", oe.getErrorMessage());
            throw new IOException("阿里OSS异常", oe);
        } catch (ClientException ce) {
            log.error("阿里OSS Client异常，Error Message:{}", ce.getMessage());
            throw new IOException("阿里OSS Client异常", ce);
        } finally {
            if (!ObjectUtils.isEmpty(ossClient)) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public void deleteFile(String objectName)  {
        // todo 创建OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(
                aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret());

        try {
            // todo 删除桶中指定对象
            ossClient.deleteObject(aliOssProperties.getBucketName(), objectName);
        } catch (OSSException oe) {
            log.error("阿里OSS异常，Error Message:{}", oe.getErrorMessage());
        } catch (ClientException ce) {
            log.error("阿里OSS Client异常，Error Message:{}", ce.getMessage());
        } finally {
            if (!ObjectUtils.isEmpty(ossClient)) {
                ossClient.shutdown();
            }
        }
    }
}
